package com.jay.tools.utils;

import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class OtherUtils {

    private static int random[] = new int[50]; // 用于存放所取的值的数组

    /**
     * 产生一组不重复的随机数
     */
    public static int[] creatRandom() {
        int number = 100;// 控制随机数产生的范围
        List<Integer> arr = new ArrayList<Integer>();
        for (int i = 0; i < 100; i++)
            arr.add(i + 1);// 为ArrayList添加元素
        for (int j = 0; j < random.length; j++) {
            int index = (int) (Math.random() * number);// 产生一个随机数作为索引
            random[j] = (int) arr.get(index);
            arr.remove(index);// 移除已经取过的元素
            number--;// 将随机数范围缩小1
        }
        return random;
    }

    private static long lastClickTime;
    private static final int CLICKSPEED = 500;

    /**
     * 防止按钮连击
     */
    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < CLICKSPEED) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 调用浏览器打开特定网址
     *
     * @param context
     * @param url     http://www.baidu.com
     */
    public static void startBrowser(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        context.startActivity(intent);
    }

    /**
     * 直接拨号，需要增加CALL_PHONE权限
     *
     * @param context
     * @param phoneNumber
     */
    @SuppressWarnings("MissingPermission")
    public static void callPhone(Context context, String phoneNumber) {
        context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)));
    }

    /**
     * 跳转至拨号界面
     *
     * @param context
     * @param phoneNumber
     */
    public static void callDial(Context context, String phoneNumber) {
        context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
    }

    /**
     * 发送短信
     *
     * @param context
     * @param phoneNumber
     * @param content
     */
    public static void sendSms(Context context, String phoneNumber, String content) {
        Uri uri = Uri.parse("smsto:" + (TextUtils.isEmpty(phoneNumber) ? "" : phoneNumber));
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        intent.putExtra("sms_body", TextUtils.isEmpty(content) ? "" : content);
        context.startActivity(intent);
    }

    /**
     * 唤醒屏幕并解锁 需要权限： <br>
     * <uses-permission android:name="android.permission.WAKE_LOCK" /> <br>
     * <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     *
     * @param context
     */
    @SuppressWarnings("MissingPermission")
    public static void wakeUpAndUnlock(Context context) {
        KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
        // 解锁
        kl.disableKeyguard();
        // 获取电源管理器对象
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        // 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
        // 点亮屏幕
        wl.acquire();
        // 释放
        wl.release();
    }

    /**
     * 判断当前App处于前台还是后台状态 <br>
     * <uses-permission android:name="android.permission.GET_TASKS" />
     *
     * @param context
     * @return
     */
    public static boolean isApplicationBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        @SuppressWarnings("deprecation")
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断当前手机是否处于锁屏(睡眠)状态
     *
     * @param context
     * @return
     */
    public static boolean isSleeping(Context context) {
        KeyguardManager kgMgr = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        return kgMgr.inKeyguardRestrictedInputMode();
    }

    /**
     * @param context
     * @return
     * @des 判断是否为手机 <br>
     * android.permission.READ_PHONE_STATE
     */
    public static boolean isPhone(Context context) {
        TelephonyManager telephony = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE;
    }

    /**
     * @param context
     * @return
     * @des 判断是不是平板
     */
    public static boolean isTablet(Context context) {
        int screenLayout = context.getResources().getConfiguration().screenLayout;
        return (screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 收集设备信息，用于信息统计分析
     *
     * @param context
     * @return
     */
    public static Properties collectDeviceInfo(Context context) {
        Properties mDeviceCrashInfo = new Properties();
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                mDeviceCrashInfo.put("VERSION_NAME", pi.versionName == null ? "not set" : pi.versionName);
                mDeviceCrashInfo.put("VERSION_CODE", pi.versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("CommUtils", "Error while collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                mDeviceCrashInfo.put(field.getName(), field.get(null));
            } catch (Exception e) {
                Log.e("CommUtils", "Error while collect crash info", e);
            }
        }
        return mDeviceCrashInfo;
    }

    /**
     * 主动回到Home，后台运行
     *
     * @param context
     */
    public static void goHome(Context context) {
        Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        context.startActivity(mHomeIntent);
    }

    /**
     * 获取MCC+MNC代码 (SIM卡运营商国家代码和运营商网络代码) <br>
     * 仅当用户已在网络注册时有效, CDMA 可能会无效<br>
     * （中国移动：46000 46002, 中国联通：46001,中国电信：46003）
     */
    public static String getNetworkOperator(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getNetworkOperator();
    }

    /**
     * 返回移动网络运营商的名字 <br>
     * (例：中国联通、中国移动、中国电信) 仅当用户已在网络注册时有效, CDMA 可能会无效)
     *
     * @param context
     * @return
     */
    public static String getNetworkOperatorName(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getNetworkOperatorName();
    }

    /**
     * 返回移动终端类型<br>
     * PHONE_TYPE_NONE :0 手机制式未知<br>
     * PHONE_TYPE_GSM :1 手机制式为GSM，移动和联通<br>
     * PHONE_TYPE_CDMA :2手机制式为CDMA，电信<br>
     * PHONE_TYPE_SIP:3<br>
     *
     * @param context
     * @return
     */
    public static int getPhoneType(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getPhoneType();
    }

}
